from General.Mapper import *
from PyQt5.QtCore import *
import functools
from DataCrawling import Spider


class RawDataToOtherType:
    """
        RawDataList元素拼接至新List
    """
    def __init__(self, object):
        self.rawData = object

    def toStrList(self):
        return [str(self.rawData.id), str(self.rawData.catchTime), str(self.rawData.ranking),
                str(self.rawData.readCount), str(self.rawData.topicId), '']


class TableDataProcess:
    """
        获取历史热门表格数据
    """
    def __init__(self):
        self.tagMapper = TagMapper()
        self.topicMapper = TopicMapper()
        self.rawDataMapper = RawDataMapper()
        self.data_list = []

    def getDataList(self, is_default=1, date=''):
        """
        :param is_default: 模式标志，为1的话获取今天的数据，否则获取date那一天的数据
        :param date: 日期时间
        :return: 历史热门表格数据List
        """
        if is_default == 1:
            now_datetime = datetime.datetime.now()
            year = now_datetime.year
            month = now_datetime.month
            day = now_datetime.day
            start_time = datetime.datetime(year, month, day, 0, 0, 0)
            end_time = datetime.datetime.now()
        else:
            date_element = date.split(' ')
            for i in range(0, 3):
                date_element[i] = int(date_element[i])
            start_time = datetime.datetime(date_element[0], date_element[1], date_element[2], 0, 0, 0)
            end_time = datetime.datetime(date_element[0], date_element[1], date_element[2], 23, 59, 59)
        self.data_list = self.rawDataMapper.getRawData(start_time, end_time)
        for i in range(0, len(self.data_list)):
            self.data_list[i] = RawDataToOtherType(self.data_list[i]).toStrList()
        for i in range(0, len(self.data_list)):
            topic = self.topicMapper.getTopicByKey(int(self.data_list[i][4]))
            tag = self.tagMapper.getTagById(topic.tagId)
            self.data_list[i][0] = topic.topicName
            self.data_list[i][4] = tag.tagName
            self.data_list[i][5] = topic.topicHost
        return self.data_list


class GetRealTimeHotSearchThread(QThread):
    """
        获取实时热搜数据的线程
    """
    get_RealTimeHotSearch = pyqtSignal(list)
    failure_signal = pyqtSignal(int)

    def __init__(self):
        super(GetRealTimeHotSearchThread, self).__init__()

    def run(self):
        while True:
            HotSearchList = Spider.Get_top_search()
            if HotSearchList == 0:
                self.failure_signal.emit(0)
            else:
                self.get_RealTimeHotSearch.emit(HotSearchList)
            QThread.sleep(3)


class GetTableDataThread(QThread):
    """
       获取历史热门表格数据的线程
    """
    get_table_data = pyqtSignal(list)

    def __init__(self, isDefault=1, date_time=''):
        super(GetTableDataThread, self).__init__()
        self.is_default = isDefault
        self.date = date_time

    def run(self):
        data = TableDataProcess().getDataList(self.is_default, self.date)
        self.get_table_data.emit(data)


class GetTopicListThread(QThread):
    """
       获取话题排行表格数据的线程
    """
    get_topicList = pyqtSignal(list)

    def __init__(self):
        super(GetTopicListThread, self).__init__()

    def run(self):
        topic_list = TopicCountProcess().getTopicList()
        self.get_topicList.emit(topic_list)


class GetTagListThread(QThread):
    """
       获取标签统计数据的线程
    """
    get_tagList = pyqtSignal(list)

    def __init__(self):
        super(GetTagListThread, self).__init__()

    def run(self):
        tag_list = BarGraphProcess().getTagList()
        self.get_tagList.emit(tag_list)


class GetWordDictThread(QThread):
    """
       获取热词数据的线程
    """
    get_wordDict = pyqtSignal(dict)

    def __init__(self):
        super(GetWordDictThread, self).__init__()

    def run(self):
        word_dict = WordCloudProcess().getWordDict()
        self.get_wordDict.emit(word_dict)


class TopicCountProcess:
    """
       获取话题排行表格数据
    """
    def __init__(self):
        self.topicCountMapper = TopicCountMapper()
        self.topicMapper = TopicMapper()
        self.tagMapper = TagMapper()
        self.topicCount_list = []
        self.topicList = []

    def getTopicList(self):
        """
        :return: 话题排行数据List
        """
        start_time = datetime.datetime.now() + datetime.timedelta(days=-1)
        end_time = datetime.datetime.now()
        self.topicCount_list = self.topicCountMapper.getTopicCount(start_time, end_time)
        self.topicCount_list.sort(key=functools.cmp_to_key(lambda x, y: y.topicCount-x.topicCount))
        for i in range(0, len(self.topicCount_list)):
            topic = self.topicMapper.getTopicByKey(self.topicCount_list[i].topicId)
            tag = self.tagMapper.getTagById(int(topic.tagId))
            topic_item_list = [topic.topicName, topic.topicDes, tag.tagName, topic.topicHost]
            self.topicList.append(topic_item_list)
        return self.topicList


class BarGraphProcess:
    """
       获取标签统计数据
    """
    def __init__(self):
        self.tagMapper = TagMapper()
        self.tagCountMapper = TagCountMapper()
        self.tagName_list = []
        self.tagFrequency_list = []
        self.tag_list = []

    def getTagList(self):
        """
        :return: 标签统计数据List
        """
        start_time = datetime.datetime.now() + datetime.timedelta(days=-1)
        end_time = datetime.datetime.now()
        tagCount_list = self.tagCountMapper.getTagCount(start_time, end_time)
        for i in range(0, len(tagCount_list)):
            tagName = self.tagMapper.getTagById(tagCount_list[i].tagId).tagName
            if tagName == 'null':
                tagName = '无标签'
            self.tagName_list.append(tagName)
            self.tagFrequency_list.append(tagCount_list[i].tagCount)
        self.tag_list = [self.tagName_list, self.tagFrequency_list]
        return self.tag_list


class WordCloudProcess:
    """
       获取热词数据
    """
    def __init__(self):
        self.wordCountMapper = WordCountMapper()
        self.wordMapper = WordMapper()
        self.wordCountList = []
        self.wordList = []
        self.wordDict = dict()
        self.wordCountDict = dict()

    def getWordDict(self):
        """
        :return: 热词数据Dict，键为热词名称，值为热词频度
        """
        start_time = datetime.datetime.now() + datetime.timedelta(days=-1)
        end_time = datetime.datetime.now()
        self.wordCountList = self.wordCountMapper.getWordCount(start_time, end_time)
        self.wordList = self.wordMapper.getAll()
        for i in range(0, len(self.wordList)):
            self.wordDict[self.wordList[i].id] = self.wordList[i].wordName
        for i in range(0, len(self.wordCountList)):
            wordName = self.wordDict[self.wordCountList[i].wordId]
            self.wordCountDict[wordName] = self.wordCountList[i].wordCount
        return self.wordCountDict
